package com.wontube.core.pub.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wontube.core.pub.AppEnvironment;


/**
 * @author yuechao
 * 
 */
public class HttpHanlderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * 处理并响应客户端请求
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		final AsyncContext ac = request.startAsync();
		// 不需要超时
		ac.setTimeout(60 * 60 * 60 * 1000);
		
		// 编码
		ac.getResponse().setCharacterEncoding(AppEnvironment.charsetName);
		final PrintWriter writer = ac.getResponse().getWriter();
		final PostProcessor processor = new HttpPostProcessor();
		processor.setAsyncContext(ac);
		processor.setRequest((HttpServletRequest)ac.getRequest());
		processor.setWriter(writer);
		processor.addListener(new HttpAsyncListener() {
			@Override
			public void onFinished() {
				ac.complete();
				processor.setAnsyncClosed(true);
			}
		});
		
		try {
			processor.process();
		} finally {
			writer.close();
		}
	}
}
